package com.xingli.jingdongshop.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class CommonUtil {
    private static final String allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static String getTimeNormal() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    //今天是周几
    public static int dayOfWeek() {
        return LocalDateTime.now().getDayOfWeek().getValue();
    }

    public static boolean getTimeNormal2Timestart(String time1, String time2) {
        return (LocalDateTime.parse(time1, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toLocalDate().isAfter(LocalDateTime.parse(time2, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toLocalDate()));
    }


    public static String getTimeDay() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    /**
     * 返回一个定长的随机字符串(只包含大小写字母、数字)
     *
     * @param length 随机字符串长度
     * @return 随机字符串
     */
    public static String randomStr(int length) {
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(allChar.charAt(random.nextInt(allChar.length())));
        }
        return sb.toString();
    }

    //判断旧的时间是否大于新的时间
    public static boolean judgeDateSize(String oldDate, String newDate) {
        return LocalDate.parse(oldDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")).
                isAfter(LocalDate.parse(newDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    }

    public static void main(String[] args) {
        System.out.println(judgeDateSize("2017-05-08", "2017-05-07"));
        System.out.println(judgeDateSize("2017-05-08", "2017-05-07"));
    }

    //Url 查询语句转化成为map
    public static HashMap<String, String> uriQuery2Map(String query) {
        String[] queryApp = query.split("&");
        HashMap<String, String> map = new HashMap<>(queryApp.length);
        for (String param : queryApp) {
            map.put(param.split("=")[0], param.split("=")[1]);
        }
        return map;
    }

    //Url 查询语句转化成为map
    public static String uriQueryValue(String query, String key) {
        String[] queryApp = query.split("&");
        for (String param : queryApp) {
            if (key.equals(param.split("=")[0])) {
                return param.split("=")[1];
            }
        }
        return "";
    }

    //xml形式的字符串转换为map集合
    public static Map<String, String> xmlStr2Map(String xmlStr) {
        Map<String, String> map = new HashMap<>();
        Document doc;
        try {
            doc = DocumentHelper.parseText(xmlStr);
            Element root = doc.getRootElement();
            List children = root.elements();
            if (children != null && children.size() > 0) {
                for (int i = 0; i < children.size(); i++) {
                    Element child = (Element) children.get(i);
                    map.put(child.getName(), child.getTextTrim());
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return map;
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String encoderByMd5(String str) {
        String re_md5 = new String();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte b[] = md.digest();

            int i;

            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }

            re_md5 = buf.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return re_md5;
    }
//    public static void main(String[] args) {
//        System.out.println(getTimeNormal());
//    }
}
